package com.hqbzl.chat;

import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import com.hqbzl.chat.model.*;
import com.hqbzl.chat.protocol.MessageCodec;
import com.hqbzl.chat.protocol.ProcotolFramDecoder;

import com.hqbzl.chat.protocol.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatClient {
    public static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    public static final MessageCodec MESSAGE_CODEC = new MessageCodec();
    // static ThreadLocal<Boolean> LOGIN_RESULT = new ThreadLocal<Boolean>();
    static AtomicBoolean LOGIN_RESULT = new AtomicBoolean(false);

    public static void main(String[] args) {
        CountDownLatch LOGIN_CDT = new CountDownLatch(1);
        final NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            final Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(new ProcotolFramDecoder());
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // 写空闲比服务器要小
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // 即可以同时作为入栈和出栈处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
							/*
							if(event.state() == IdleState.READER_IDLE){
								log.debug("已经5秒没能读到数据了");
							}
                          */
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug("已经3秒没写到数据了， 发心跳包");
                                ctx.writeAndFlush(new PingRequestMessage());
                            }

                            //super.userEventTriggered(ctx, evt);
                        }
                    });

                    ch.pipeline().addLast("clientHandler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            new Thread(() -> {
                                final Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名: ");
                                final String userName = scanner.nextLine();
                                System.out.println("请输入密码: ");
                                final String password = scanner.nextLine();
                                final LoginRequestMessage build = LoginRequestMessage.builder().userName(userName)
                                        .password(password).build();
                                // 发消息
                                ctx.writeAndFlush(build);

                                try {
                                    LOGIN_CDT.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                if (!LOGIN_RESULT.get()) {
                                    log.debug("login fail");
                                    ctx.channel().close();
                                    return;
                                }
                                boolean exit = true;
                                while (true && exit) {
                                    System.out.println("=====================================");
                                    System.out.println("send [userName] [content]");
                                    System.out.println("gsend [groupName] [content]");
                                    System.out.println("gcreate [groupName] [m1,m2,m3]");
                                    System.out.println("gmemebers [groupName]");
                                    System.out.println("gjoin [groupName]");
                                    System.out.println("gquit [groupName]");
                                    System.out.println("quit");
                                    System.out.println("=====================================");
                                    String command = scanner.nextLine();
                                    String[] c = command.split(" ");
                                    switch (c[0]) {
                                        case "send":
                                            SendMessage sendMsg = SendMessage.builder().userName(userName).targetUser(c[1])
                                                    .context(c[2]).build();

                                            ctx.writeAndFlush(sendMsg);
                                            break;
                                        case "gsend":
                                            GSendMessage sendGroupMsg = GSendMessage.builder().groupName(c[1]).context(c[2])
                                                    .build();
                                            ctx.writeAndFlush(sendGroupMsg);
                                            break;
                                        case "gcreate":
                                            GCreageMessage gCreateMsg = GCreageMessage.builder().groupName(c[1])
                                                    .members(c[2]).build();
                                            ctx.writeAndFlush(gCreateMsg);
                                            break;
                                        case "gmemebers":
                                            GMemgersMessage gMemberMsg = GMemgersMessage.builder().groupName(c[1]).build();
                                            ctx.writeAndFlush(gMemberMsg);
                                            break;
                                        case "gjoin":
                                            GJoinGroupMessage gJoinMsg = GJoinGroupMessage.builder().groupName(c[1])
                                                    .userName(userName).build();
                                            ctx.writeAndFlush(gJoinMsg);
                                            break;
                                        case "gquit":
                                            GExitGroupMessage gExitMsg = GExitGroupMessage.builder().groupName(c[1])
                                                    .userName(userName).build();
                                            ctx.writeAndFlush(gExitMsg);
                                            break;
                                        case "quit":
                                            log.debug("bye byte");
                                            ctx.channel().close();
                                            exit = false;
                                            break;
                                    }

                                }
                            }, "system-in").start();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.debug("channelRead: {}", msg);
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage login = (LoginResponseMessage) msg;
                                if (login.isResult()) {
                                    LOGIN_RESULT.set(Boolean.TRUE);
                                } else {
                                    LOGIN_RESULT.set(Boolean.FALSE);
                                }
                            }
                            if (msg instanceof PingResponseMessage) {
                                log.debug("receive server: {}", msg);
                            }
                            if (msg instanceof Group) {

                            }
                            LOGIN_CDT.countDown();
                            super.channelRead(ctx, msg);
                        }
                    });
                }
            });
            final Channel channel = bootstrap.connect("localhost", 7788).sync().channel();
            // 连接创建好
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            group.shutdownGracefully();
        }
    }
}
